menus = function() {
	//已点击菜单项
	var MENUSONCLICKITEM = null;
	//var MENUSONCLICKLEAF = -1;
	//添加修改窗体定义
	var MENUSADDOREDITWIN = null;
	//选择图片窗体定义
	var MENUIMGWIN = null;
	//菜单属性STORE
	var MENUSLEVELSTORE = new Store({
		fields: ['id', 'str'],
		data: [
		   { id: 0, str: '可分配' },
		   { id: 1, str: '不可分配' }
		]
	});
	//菜单等级STORE
	var MENUSLEAFSTORE = new Store({
		fields: ['id', 'str'],
		data: [
		   { id: 0, str: '第一级(主题)' },
		   { id: 1, str: '第二级(栏目)' },
		   { id: 2, str: '第三级(功能)' },
		   { id: 3, str: '第四级(按钮)' }
		]
	});
	//菜单权限STORE
	var MENUSACTIONSTORE = new Store({
		fields: ['id', 'code', 'remark'],
		proxy: {
	        type: 'ajax',
	        url: '../admin/menu.do?indextoaction'
	    },
	    autoLoad: false
	});
	
	return {
		/*--------------------------------------窗体定义--------------------------------------------*/
		//定义菜单窗体
		panel : function() {
			//初始化菜单权限STORE
			MENUSACTIONSTORE.load();
			//菜单树形STORE
			var menustore = new TreeStore({
				fields: ['id', 'text', 'aleaf', 'leaf'],
		        root: {
		        	id: 0,
		            expanded: true,
		            text: '所有菜单',
		            icon: '../manage/pic/menu/6.png'
		        },
		        proxy: {
		            type: 'ajax',
		            url: '../admin/menu.do?index',
		            reader: {
		                type: 'json',
		                root: 'children'
		            }
		        }
		    });
			MENUSONCLICKITEM = menustore.getRootNode();
			//菜单树形Tree
			var tree = new Tree({
		        store: menustore,
		        id: 'menutree',
		        region: 'west',
		        hideHeaders: true,
		        width: '25%',
		        lines: false,
		        disableSelection: true,
		        title: '菜单布局',
		        tbar: [{
		        	text: '刷新',
					scale: 'medium',
					iconCls: 'icon-refresh',
					handler: function() {
						menustore.load();
					}
		        }, "-", {
		        	text: '全部展开',
		        	scale: 'medium',
		        	iconCls: 'icon-open',
		        	handler: function() {
		        		tree.collapseAll();
		        		tree.expandAll();
		        	}
		        }],
		        listeners: {
		        	itemclick: function(fn, record, item, index, e, eOpts) {
		        		MENUSONCLICKITEM = record;
		        		menus.loadDetailAction();
		        	}
		        }
			});
			
			//菜单明细STORE
			var detailstore = new Store({
				fields: ['id', 'name', 'leaf', 'level', 'action', 'namespace', 'icon'],
				proxy: {
			        type: 'ajax',
			        url: '../admin/menu.do?indextodetail'
			    },
			    autoLoad: false
			});
			detailstore.load({params: {id: MENUSONCLICKITEM.get('id')}});
			//菜单明细GRID
			var grid = new Grid({
				title: '菜单明细列表',
				id: 'menugrid',
				region: 'center',
				store: detailstore,
				minColumnWidth: 35,
				stripeRows: true,
				tbar: [{
		        	text: '刷新',
					scale: 'medium',
					iconCls: 'icon-refresh',
					handler: function() {
						menus.loadDetailAction();
					}
		        }, "-", {
					id: 'menuAdd',
					text: '添加',
					scale: 'medium',
					iconCls: 'icon-add',
					disabled: true,
					handler: function() {
						menus.addMenuAction();
					}
				}, "-", {
					id: 'menuEdit',
					text: '修改',
					scale: 'medium',
					iconCls: 'icon-edit',
					disabled: true,
					handler: function() {
						menus.editMenuAction();
					}
				}, "-", {
					id: 'menuRemove',
					text: '删除',
					scale: 'medium',
					iconCls: 'icon-remove',
					disabled: true,
					handler: function() {
						menus.removeAction();
					}
				}],
				columns: [
		             new Ext.grid.RowNumberer(),
		             {header: '序号', dataIndex: 'id', hidden: true},
		             {header: '菜单名称', dataIndex: 'name', width: 175},
		             {header: '菜单等级', dataIndex: 'leaf', width: 150, renderer: function(v) {
		            	 return MENUSLEAFSTORE.getById(v).get('str');
		             }},
		             {header: '属性', dataIndex: 'level', width: 150, renderer: function(v) {
		            	 return MENUSLEVELSTORE.getById(v).get('str');
		             }},
		             {header: '关联权限', dataIndex: 'action', width: 150, renderer: function(v) {
		            	 if (v == 0) return "";
		            	 return MENUSACTIONSTORE.getById(v).get('remark');
		             }},
		             {header: '命名空间', dataIndex: 'namespace', width: 125},
		             {header: '图片', dataIndex: 'icon', width: 100, renderer: function(v) {
		            	 return "<img src='" + v + "'/>";
		             }}
				]
			});
			
			
			var panel = new Panel({
				border: false,
				layout: 'border',
				items: [tree, grid]
			});
			
			return panel;
		},
		
		//添加修改菜单窗体
		addOrEditWin: function() {
			if (MENUSADDOREDITWIN == null) {
				MENUSADDOREDITWIN = new Window({
					id: 'menuAddOrEditWin',
				    title: '菜单信息编辑',
				    height: 250,
				    width: 450,
				    layout: 'fit',
				    closeAction: "hide",
				    modal: true,
				    items: [{
				    	xtype: 'form',
				    	id: 'menuAddOrModifyForm',
				    	frame: false,
						autoHeight: true,
						bodyPadding: 15,
						fieldDefaults: {
				            labelWidth: 75
				        },
				        defaultType: 'textfield',
				        defaults: {
				            anchor: '95%'
				        },
				        items: [{
				        	name: 'id',
				        	hidden: true
				        }, {
				        	fieldLabel: '菜单名称',
				        	name: 'name',
				            allowBlank: false
				        }, {
				        	xtype: 'combo',
			             	fieldLabel: '属性',
			             	name: 'level',
			             	store: MENUSLEVELSTORE,
			                displayField: 'str',
			                valueField: 'id',
			                queryMode: 'local',
			                editable: false,
				            allowBlank: false
				        }, {
				        	xtype: 'combo',
			             	fieldLabel: '关联权限',
			             	name: 'action',
			             	store: MENUSACTIONSTORE,
			                displayField: 'remark',
			                valueField: 'id',
			                queryMode: 'local',
			                forceSelection: true,
				            allowBlank: false,
			                listConfig: {
			                    getInnerTpl: function() {
			                        return '<div data-qtip="{remark}. {code}">{remark} ({code})</div>';
			                    }
			                }
				        }, {
				        	fieldLabel: '命名空间',
				        	name: 'namespace',
				            allowBlank: false
				        }, {
				    		xtype: 'fieldcontainer',
				            fieldLabel: '图片',
				            layout: 'hbox',
				            items: [{
				            	xtype: 'image',
				            	id: 'menuImg',
				            	width: 16,
				            	style: 'margin-top: 4px; margin-right: 10px',
				            	src: '../manage/pic/menu/default.png'
				            }, {
				    			xtype: 'button',
				    			text: '选择',
				    			handler: function() {
				    				var fom = this.up('form').getForm(); 
				    				menus.chooseImgAction(fom);
				    			}
				    		}]
				    	}, {
				    		name: 'icon',
				    		hidden: true
				    	}],
				        buttons: [{
				        	text: '确定',
				        	handler: function() {
				        		var fom = this.up('form').getForm();
				        		if (fom.isValid()) {
				        			menus.sumbitAction(fom);
				        		}
				        	}
				        }, {
				        	text: '取消',
				        	handler: function() {
				        		MENUSADDOREDITWIN.hide();
				        	}
				        }]
				    }],
			        listeners: {
			        	hide: function(fn, eOpts) {
			        		this.down('form').getForm().reset();
			        	}
			        }
				});
			}
			MENUSADDOREDITWIN.show();
		},
		
		//选择图片
		chooseImgWin: function(fom) {
			
			var store = new Store({
				fields: ['id', 'path'],
				proxy: {
			        type: 'ajax',
			        url: '../admin/menu.do?indextoimg'
			    },
			    autoLoad: true
			});
			
			var dataview = Ext.create('Ext.view.View', {
		        deferInitialRefresh: false,
		        store: store,
		        tpl  : Ext.create('Ext.XTemplate',
		            '<tpl for=".">',
		                '<div class="photoes">',
		                    '<img src="{path}"/>',
		                '</div>',
		            '</tpl>'
		        ),
		        id: 'photoes',
		        itemSelector: 'div.photoes',
		        overItemCls : 'photoes-hover',
		        autoScroll  : true,
		        listeners: {
		        	itemdblclick: function(fn, record, item, index, e, eOpts) {
		        		fom.findField('icon').setValue(record.get('path'));
		        		Ext.getCmp('menuImg').setSrc(record.get('path'));
		        		MENUIMGWIN.hide();
	                }
	            }
		    });
			
			if (MENUIMGWIN == null) {
				MENUIMGWIN = new Window({
					id: 'menuChooseImgWin',
				    title: '选择图片',
				    height: 250,
				    width: 450,
				    layout: 'fit',
				    closeAction: "hide",
				    modal: true,
				    items: [{
				    	xtype: 'form',
				    	frame: false,
						autoHeight: true,
						bodyPadding: 5,
						items: dataview
				    }]
				});
			}
			MENUIMGWIN.show();
		},
		
		/*--------------------------------------事件定义--------------------------------------------*/
		//刷新菜单明细事件
		loadDetailAction: function() {
			Ext.getCmp('menugrid').getStore().load({params: {id: MENUSONCLICKITEM.get('id')}});
		},
		
		//添加菜单触发事件
		addMenuAction: function() {
			if (MENUSONCLICKITEM.get('aleaf') == 3) {
				Ext.Msg.alert('提示', '该菜单为第四级(按钮),无法添加子菜单！');
				return false;
			}
			menus.addOrEditWin();
			Ext.getCmp('menuImg').setSrc('../manage/pic/menu/default.png');
			var fom = Ext.getCmp('menuAddOrModifyForm').getForm();
			fom.findField('icon').setValue('../manage/pic/menu/default.png');
			var isFlag = false;
			if (MENUSONCLICKITEM.get('aleaf') < 1) {
				isFlag = true;
			}
			fom.findField('action').setDisabled(isFlag);
			fom.findField('namespace').setDisabled(isFlag);
		},
		
		//修改菜单触发事件
		editMenuAction: function() {
			var sel = Ext.getCmp('menugrid').getSelectionModel().getSelection();
			if (sel.length < 1) {
				Ext.Msg.alert('提示', '请选择要修改的菜单！');
				return false;
			} else {
				menus.addOrEditWin();
				var fom = Ext.getCmp('menuAddOrModifyForm').getForm();
				fom.loadRecord(sel[0]);
				Ext.getCmp('menuImg').setSrc(sel[0].get('icon'));
				var isFlag = false;
				if (sel[0].get('leaf') < 2) {
					isFlag = true;
				}
				fom.findField('action').setDisabled(isFlag);
				fom.findField('namespace').setDisabled(isFlag);
			}
		},
		
		//选择图片触发事件
		chooseImgAction: function(fom) {
			menus.chooseImgWin(fom);
		},
		
		//提交确认事件
		sumbitAction: function(fom) {
			var url = '../admin/menu.do?edit';
			var id = fom.findField('id').value;
			if (id == '') {
				url = '../admin/menu.do?add';
			}
			FormSubmit(fom, url, {
				parent: MENUSONCLICKITEM.get('id')
			}, function(obj) {
				var store = Ext.getCmp('menutree').getStore();
				var tnode = store.getRootNode();
				if (MENUSONCLICKITEM.get('id') != 0) {
					tnode = store.getNodeById(MENUSONCLICKITEM.get('id'));
				}
				if (id == '') {
					var isleaf = obj.leaf == 3? true : false;
					tnode.set('leaf', false);
					tnode.set('expandable', true);
					tnode.appendChild({
						id: obj.id,
						text: fom.findField('name').value,
						icon: fom.findField('icon').value,
						aleaf: MENUSONCLICKITEM.get('aleaf') + 1,
						leaf: true
					});
				} else {
					tnode = store.getNodeById(id);
					tnode.set('text', fom.findField('name').value);
					tnode.set('icon', fom.findField('icon').value);
				}
				menus.loadDetailAction();
				MENUSADDOREDITWIN.hide();
			});
		},
		
		//删除菜单事件
		removeAction: function() {
			var sel = Ext.getCmp('menugrid').getSelectionModel().getSelection();
			if (sel.length < 1) {
				Ext.Msg.alert('提示', '请选择要删除的菜单！');
			} else {
				Ext.MessageBox.confirm('确认', '您确认要删除该菜单吗？', function(btn) {
					if (btn == "yes") {
						var res = RequestByUrl('../admin/menu.do?remove', {
							id: sel[0].get('id')
						});
						var store = Ext.getCmp('menutree').getStore();
						var tnode = store.getNodeById(sel[0].get('id'));
						var pnode = tnode.parentNode;
						pnode.removeChild(tnode);
						if (pnode.childNodes.length == 0) {
							pnode.set('leaf', true);
							pnode.set('expandable', false);
						}
						menus.loadDetailAction();
						Ext.Show.msg(res.title, '');
					}
				});
			}
		}
	};
}();